#!/bin/bash

set -e
sudo -v

# Variable for displaying log
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
MAGENTA=$(tput setaf 5)
NC=$(tput sgr0)
BOLD=$(tput bold)
INFO=$(tput setaf 3)
FILE_NAME=$0


openedge_array=("ia_video_analytics" "ia_video_ingestion" "ia_etcd_ui" "ia_opcua_export" "ia_imagestore" "ia_etcd_provision" "ia_etcd" "ia_web_visualizer" "ia_visualizer" "ia_grafana")
basic_array=("ia_video_common" "ia_openvino_base" "ia_common" "ia_eiibase")
ts_array=("ia_telegraf" "ia_influxdbconnector" "ia_kapacitor" "ia_rest_export" "ia_opcua_export")
eiigui_array=("surface_defect_video_ingestion" "surface_defect_opcua_export" "surface_defect_tcp_export" "textline_video_ingestion" "textline_opcua_export" "textline_tcp_export" "safety_gear_video_ingestion" "safety_gear_tcp_export" "safety_gear_opcua_export" "pcb_video_ingestion" "pcb_video_analytics" "pcb_opcua_export" "pcb_tcp_export" "fly_camera_video_ingestion" "fly_camera_opcua_export" "fly_camera_tcp_export" "qrcode_detect_video_ingestion" "qrcode_detect_opcua_export" "qrcode_detect_tcp_export" "raspberrypi_video_ingestion" "raspberrypi_video_analytics" "raspberrypi_opcua_export" "raspberrypi_tcp_export" "text_spotting_video_ingestion" "text_spotting_opcua_export" "text_spotting_tcp_export")
depend_array=()
openedge_tag="openedgeinsights"
eiigui="eiigui"
eii_version_array=("2.6", "2.6.1", "3.0")
eii_ver=""
hub_name="isdchina"
CUR_DIR=$PWD
BUILD_DIR=$CUR_DIR/build



Usage()
{
    echo
	echo "${BOLD}${INFO}==================================================================================${NC}"
    echo
	echo "${BOLD}${GREEN}Usage :: $FILE_NAME -h [OPTION...] ${NC}"
    echo
	echo "${INFO}List of available options..."
    echo
	echo "${INFO}--pull			add the eii version to pull eii and eiigui images"${NC}
    echo
	echo "${INFO}--eii_tar		add the eii version to tar your loacal eii images"${NC}
    echo
	echo "${INFO}--gui_tar		add the eii version to tar your loacal eiigui images"${NC}
    echo
	echo "${INFO}--all			add the eii version to pull&tar eii and eiigui images"${NC}
    echo
	echo "${INFO}--help			display this help and exit"${NC}
    echo
	echo "${INFO}-h			display this help and exit"${NC}
	echo "use cases sample..."
        echo "${BOLD}${MAGENTA}

                1. RUNS WITH eii 2.6.1
                ./eii_docker.sh --pull=2.6.1
                ./eii_docker.sh --eii_tar=2.6.1
                ./eii_docker.sh --gui_tar=2.6.1
                ./eii_docker.sh --all_tar=2.6.1
                2. RUNS WITH eii 3.0
                ./eii_docker.sh --pull=3.0
                ./eii_docker.sh --eii_tar=3.0
                ./eii_docker.sh --gui_tar=3.0
                ./eii_docker.sh --all_tar=3.0

        "
    
	echo "${INFO}===================================================================================${NC}"
	exit 1
}

parse_commandLine_args()
{
	if [ $# == "0" ];then
		return;
	fi
	
	# echo "${INFO}Reading the command line args...${NC}"
	for ARGUMENT in "$@"
	do
	    KEY=$(echo $ARGUMENT | cut -f1 -d=)
	    VALUE=$(echo $ARGUMENT | cut -f2 -d=)   

	    case "$KEY" in
		    --pull) pull_images ;;
		    --eii_tar) tar_images eii ;;
		    --gui_tar) tar_images eiigui ;;
		    --all) pull_tar_images ;;   
		    --help) Usage ;; 
            -h) Usage ;; 
		     *) echo "${RED}Invalid arguments passed..${NC}"; Usage; ;;  
	    esac    
	done
}

pull_images()
{
        get_eii_version
	# pulling the depend images
	echo "-----------start to pull images-----------"
	for item in ${depend_array[*]};do
		docker pull $item
		
	done

	total_array=(${openedge_array[@]} ${basic_array[@]})
	# total_array=(${ts_array[@]})
	num=1
	for item in ${total_array[*]};do
		echo "pulling images: $item"
		docker pull $hub_name/$item:$eii_ver
		if [[ "$num" -ge "1" && "$num" -le "${#openedge_array[@]}" ]];then
			docker tag $hub_name/$item:$eii_ver $openedge_tag/$item:$eii_ver
			echo "In $openedge_tag tag"
		elif [[ "$num" -gt "${#openedge_array[@]}" && "$num" -le "((${#openedge_array[@]}+${#basic_array[@]}))" ]];then
			docker tag $hub_name/$item:$eii_ver $item:$eii_ver
			echo "In basic tag"
		else
			docker tag $hub_name/$item:$eii_ver $eiigui/$item:$eii_ver
			echo "In $eiigui tag"
		fi
		let num+=1
		docker rmi $hub_name/$item:$eii_ver
	
	done
	echo "pull all images done"
	echo "---------------------------------------"
}

tar_images()
{
        get_eii_version
	if [ "$1" == "eii" ];then
		echo "-----------start to tar eii images-----------"
		total_array=(${openedge_array[@]} ${basic_array[@]})
		num=1
		images_str=""
		for item in ${total_array[*]};do
			if [[ "$num" -ge "1" && "$num" -le "${#openedge_array[@]}" ]];then
				images_str="$images_str$openedge_tag/$item:$eii_ver "
			elif [[ "$num" -gt "${#openedge_array[@]}" && "$num" -le "((${#openedge_array[@]}+${#basic_array[@]}))" ]];then
				images_str="$images_str$item:$eii_ver "
			else
				echo "total_array lenth fault"
				exit 1
			fi
			let num+=1
		done
		for item in ${depend_array[*]};do
			images_str="$images_str$item "
		done
		echo $images_str
		if [ -d "$BUILD_DIR/eii" ];then
			docker save $images_str -o $BUILD_DIR/eii/eii_images.tar
		else
			echo "Folder $BUILD_DIR/eii is not exist"
		fi
		echo "-----------finish tar eii images done-----------"
	elif [ "$1" == "eiigui" ];then
		echo "-----------start to tar eiigui images-----------"
		total_array=(${eiigui_array[@]})
		images_str=""
		for item in ${total_array[*]};do
			images_str="$images_str$eiigui/$item:$eii_ver "
		done
		echo $images_str
		if [ -d "$BUILD_DIR/eii" ];then
			docker save $images_str -o $BUILD_DIR/eii/eiigui_images.tar
		else
			echo "Folder $BUILD_DIR/eii is not exist"
		fi
		echo "-----------finish tar eiigui images done-----------"
	else
		echo "params illegal"
		exit 1
	fi
	echo "---------------------------------------"
	
}

pull_tar_images()
{
	pull_images
	tar_images eii
	tar_images eiigui
}

docker_verification_installation()
{
    echo "Verifying if docker already exists."
    cur_v=$(echo $(docker --version) | cut -d"n" -f 2 | cut -d"," -f 1)
	if [ -z $cur_v ];then
		echo "${INFO}docker is not installed on machine${NC}"
		exit 0
	else
		echo "${INFO}docker is already installed on machine${NC}"
	fi
}

get_eii_version(){
	if echo "${eii_version_array[@]}" | grep -w $VALUE &>/dev/null; then
		eii_ver=$VALUE
		echo $eii_ver
	else
		echo "eii version must in $(echo "${eii_version_array[*]}")"
		exit 1
	fi
	if [ "$eii_ver" == "2.6" ];then
		depend_array=("ubuntu:20.04" "openvino/ubuntu20_data_runtime:2021.4")
	elif [ "$eii_ver" == "2.6.1" ];then
		depend_array=("ubuntu:20.04" "openvino/ubuntu20_data_runtime:2021.4.1")
	elif [ "$eii_ver" == "3.0" ];then
		depend_array=("ubuntu:20.04" "openvino/ubuntu20_data_runtime:2021.4.2")
		openedge_array=("ia_video_analytics" "ia_video_ingestion" "ia_etcd_ui" "ia_imagestore" "ia_configmgr_agent" "ia_web_visualizer" "ia_visualizer" "ia_grafana")
	else
		depend_array=()
	fi
}

startTime=`date +%Y%m%d-%H:%M:%S`
startTime_s=`date +%s`

docker_verification_installation
if [ $# -ne "0" ];then
	parse_commandLine_args "$@"
else
	echo "${BOLD}${INFO}Please type at least 1 params${NC}"
	echo "${BOLD}${INFO}Usage :: $FILE_NAME -h [OPTION...] ${NC}"
fi

endTime=`date +%Y%m%d-%H:%M:%S`
endTime_s=`date +%s`
sumTime=$[ $endTime_s - $startTime_s ]
echo "$startTime ---> $endTime" "Total: $sumTime seconds"
echo " "
